public class Solution {
    public int reverse(int x) {
        int res = 0;
        while(x != 0) {
            if (x < 10 && x > -10) {
                if (res > (Integer.MAX_VALUE / 10)) {
                    return 0;
                }

                if (res == (Integer.MAX_VALUE / 10) && x > (Integer.MAX_VALUE % 10)) {
                    return 0;
                }

                if (res < (Integer.MIN_VALUE / 10)) {
                    return 0;
                }

                int a = Integer.MIN_VALUE % 10;
                int b = Integer.MIN_VALUE / 10;
                if (res == (Integer.MIN_VALUE / 10) && x < (Integer.MIN_VALUE % 10)) {
                    return 0;
                }
            }
            int mod = x % 10;
            res = res * 10 + mod;
            x /= 10;
        }
        return res;
    }

    public int reverse2(int x) {
        //防止负数出现“545454-”的情况
        String xString = String.valueOf(Math.abs(x));
        String targetString = new StringBuilder(xString).reverse().toString();
        
        try {
            int res = Integer.valueOf(targetString);
            return x < 0 ? -res : res;
        } catch (NumberFormatException exception) {
            return 0;
        }
    }
}
